<template>
  <div 
    class="racing-game-wrapper min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-gray-900 to-black p-4"
  >
    <!-- 返回按钮 -->
    <button 
      @click="$router.push('/')" 
      class="absolute top-4 left-4 px-6 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white transition-all flex items-center gap-2"
    >
      <span class="text-xl">←</span> 返回主菜单
    </button>

    <div 
      class="game-container" 
      @keydown="handleKeyPress" 
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      tabindex="0" 
      ref="gameContainer"
    >
      <!-- Start Screen -->
      <div v-if="!gameStarted" class="start-screen">
        <h1 class="game-title text-5xl font-bold mb-8 text-white">极速赛车</h1>
        <div class="difficulty-selector mb-8">
          <h3 class="text-xl mb-4 text-white">选择难度:</h3>
          <div class="difficulty-buttons flex gap-4">
            <button 
              @click="setDifficulty('easy')" 
              :class="{ 
                'bg-green-500': difficulty === 'easy',
                'hover:bg-green-600': difficulty === 'easy',
                'bg-white/10 hover:bg-white/20': difficulty !== 'easy'
              }"
              class="px-6 py-2 rounded-lg text-white transition-all"
            >简单</button>
            <button 
              @click="setDifficulty('medium')" 
              :class="{ 
                'bg-yellow-500': difficulty === 'medium',
                'hover:bg-yellow-600': difficulty === 'medium',
                'bg-white/10 hover:bg-white/20': difficulty !== 'medium'
              }"
              class="px-6 py-2 rounded-lg text-white transition-all"
            >中等</button>
            <button 
              @click="setDifficulty('hard')" 
              :class="{ 
                'bg-red-500': difficulty === 'hard',
                'hover:bg-red-600': difficulty === 'hard',
                'bg-white/10 hover:bg-white/20': difficulty !== 'hard'
              }"
              class="px-6 py-2 rounded-lg text-white transition-all"
            >困难</button>
          </div>
        </div>
        <div class="high-scores mb-8">
          <h3 class="text-xl mb-4 text-white">最高分:</h3>
          <ul class="flex flex-col gap-2">
            <li 
              v-for="(score, index) in topScores" 
              :key="index"
              class="text-white/80"
            >
              {{ score }}分
            </li>
          </ul>
        </div>
        <button 
          @click="startGame" 
          class="start-button px-8 py-3 bg-gradient-to-r from-purple-600 to-pink-600 rounded-lg text-white text-xl font-bold hover:from-purple-700 hover:to-pink-700 transition-all transform hover:scale-105"
        >
          开始游戏
        </button>
      </div>

      <!-- Game Screen -->
      <template v-else>
        <div class="road-container">
          <div class="road" :style="{ animationDuration: `${roadSpeed}ms` }">
            <div class="road-lines"></div>
          </div>
          <div 
            v-for="obstacle in obstacles" 
            :key="obstacle.id" 
            class="obstacle"
            :style="{ left: obstacle.x + 'px', top: obstacle.y + 'px' }"
          >
            <img :src="obstacle.type === 'car' ? '/obstacle-car.png' : '/barrier.png'" alt="obstacle" />
          </div>
          <div class="player-car" :style="{ left: carPosition + 'px' }">
            <img src="/player-car.png" alt="player car" />
          </div>
        </div>

        <!-- Game UI -->
        <div class="game-ui">
          <div class="score-panel">
            <div class="score">得分: {{ score }}</div>
            <div class="speed">速度: {{ speed }} km/h</div>
          </div>
          <div class="mobile-controls" v-if="isMobile">
            <button @touchstart="moveLeft" @touchend="stopMoving" class="control-btn left">←</button>
            <button @touchstart="moveRight" @touchend="stopMoving" class="control-btn right">→</button>
          </div>
        </div>
      </template>

      <!-- Game Over Screen -->
      <div v-if="gameOver" class="game-over">
        <h2 class="text-4xl font-bold mb-4 text-white">游戏结束</h2>
        <p class="text-2xl mb-4 text-white">你的得分: {{ score }}</p>
        <p v-if="isNewHighScore" class="new-high-score text-3xl text-yellow-400 mb-6">新纪录！</p>
        <div class="flex gap-4">
          <button 
            @click="restartGame" 
            class="restart-button px-6 py-2 bg-gradient-to-r from-purple-600 to-pink-600 rounded-lg text-white hover:from-purple-700 hover:to-pink-700 transition-all"
          >
            重新开始
          </button>
          <button 
            @click="$router.push('/')" 
            class="px-6 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white transition-all"
          >
            返回主菜单
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import soundEffects from '../utils/soundEffects';

// 游戏状态
const gameContainer = ref(null);
const gameStarted = ref(false);
const gameOver = ref(false);
const score = ref(0);
const speed = ref(0);
const carPosition = ref(175);
const obstacles = ref([]);
const gameLoop = ref(null);
const difficulty = ref('medium');
const topScores = ref([]);
const isNewHighScore = ref(false);
const isMobile = ref(false);
const touchStartX = ref(0);
const roadSpeed = ref(2000);
const engineSound = ref(null);

// 难度设置
const difficultySettings = {
  easy: { obstacleSpeed: 3, spawnRate: 0.015, speedIncrease: 0.5 },
  medium: { obstacleSpeed: 5, spawnRate: 0.02, speedIncrease: 1 },
  hard: { obstacleSpeed: 7, spawnRate: 0.025, speedIncrease: 1.5 }
};

// 初始化
onMounted(() => {
  loadHighScores();
  checkMobile();
  window.addEventListener('keydown', handleKeyPress);
  window.addEventListener('resize', checkMobile);
});

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyPress);
  window.removeEventListener('resize', checkMobile);
  clearInterval(gameLoop.value);
  if (engineSound.value) {
    soundEffects.stopSound(engineSound.value);
  }
});

// 游戏控制
const setDifficulty = (level) => {
  difficulty.value = level;
};

const startGame = () => {
  gameStarted.value = true;
  gameOver.value = false;
  score.value = 0;
  speed.value = 0;
  obstacles.value = [];
  engineSound.value = soundEffects.createEngineSound();
  gameLoop.value = setInterval(updateGame, 20);
  gameContainer.value.focus();
};

const restartGame = () => {
  gameOver.value = false;
  isNewHighScore.value = false;
  startGame();
};

// 移动控制
const handleKeyPress = (e) => {
  if (e.key === 'ArrowLeft' && carPosition.value > 0) {
    moveLeft();
  } else if (e.key === 'ArrowRight' && carPosition.value < 350) {
    moveRight();
  }
};

const moveLeft = () => {
  if (carPosition.value > 0) {
    carPosition.value -= 10;
  }
};

const moveRight = () => {
  if (carPosition.value < 350) {
    carPosition.value += 10;
  }
};

// 触摸控制
const handleTouchStart = (e) => {
  touchStartX.value = e.touches[0].clientX;
};

const handleTouchMove = (e) => {
  const touchX = e.touches[0].clientX;
  const diff = touchX - touchStartX.value;
  
  if (Math.abs(diff) > 10) {
    if (diff > 0) {
      moveRight();
    } else {
      moveLeft();
    }
    touchStartX.value = touchX;
  }
};

const handleTouchEnd = () => {
  touchStartX.value = 0;
};

// 游戏逻辑
const updateGame = () => {
  const settings = difficultySettings[difficulty.value];
  speed.value = Math.floor(50 + (score.value / 100));
  roadSpeed.value = 2000 - (speed.value * 10);
  score.value++;

  if (score.value % 100 === 0) {
    soundEffects.createScoreSound();
  }

  // 更新引擎声音频率
  if (engineSound.value) {
    engineSound.value.updateSpeed(speed.value);
  }

  // 移动障碍物
  obstacles.value.forEach(obstacle => {
    obstacle.y += settings.obstacleSpeed + (speed.value / 20);
  });

  // 移除离开屏幕的障碍物
  obstacles.value = obstacles.value.filter(obstacle => obstacle.y < 600);

  // 添加新的障碍物
  if (Math.random() < settings.spawnRate) {
    obstacles.value.push({
      id: Date.now(),
      x: Math.random() * 350,
      y: -50,
      type: Math.random() > 0.5 ? 'car' : 'barrier'
    });
  }

  // 碰撞检测
  if (checkCollision()) {
    endGame();
  }
};

const checkCollision = () => {
  const carRect = {
    left: carPosition.value + 10,
    right: carPosition.value + 40,
    top: 500,
    bottom: 550
  };

  return obstacles.value.some(obstacle => {
    const obstacleRect = {
      left: obstacle.x + 10,
      right: obstacle.x + 40,
      top: obstacle.y,
      bottom: obstacle.y + 50
    };

    return !(carRect.left > obstacleRect.right || 
             carRect.right < obstacleRect.left || 
             carRect.top > obstacleRect.bottom ||
             carRect.bottom < obstacleRect.top);
  });
};

const endGame = () => {
  soundEffects.createCollisionSound();
  if (engineSound.value) {
    soundEffects.stopSound(engineSound.value);
    engineSound.value = null;
  }
  clearInterval(gameLoop.value);
  gameOver.value = true;
  updateHighScores();
};

// 高分系统
const loadHighScores = () => {
  const saved = localStorage.getItem('highScores');
  topScores.value = saved ? JSON.parse(saved) : [];
};

const updateHighScores = () => {
  const newScore = score.value;
  topScores.value.push(newScore);
  topScores.value.sort((a, b) => b - a);
  topScores.value = topScores.value.slice(0, 5);
  localStorage.setItem('highScores', JSON.stringify(topScores.value));
  isNewHighScore.value = newScore === topScores.value[0];
};

const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768;
};
</script>

<style scoped>
.racing-game-wrapper {
  min-height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
}

.game-container {
  width: min(90vw, 600px);
  height: min(90vh, 800px);
  margin: 0 auto;
  position: relative;
  overflow: hidden;
  background-color: #1a1a1a;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.road-container {
  width: 100%;
  height: 100%;
  position: relative;
  perspective: 500px;
}

.road {
  width: 100%;
  height: 100%;
  background: url('/road-texture.png') repeat-y;
  background-size: 100% auto;
  animation: scrollRoad linear infinite;
  transform-style: preserve-3d;
  transform: rotateX(60deg);
}

@keyframes scrollRoad {
  from { background-position: 0 0; }
  to { background-position: 0 600px; }
}

.player-car {
  width: 50px;
  height: 80px;
  position: absolute;
  bottom: 20px;
  transition: left 0.1s;
  z-index: 10;
}

.player-car img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.obstacle {
  width: 50px;
  height: 50px;
  position: absolute;
  z-index: 5;
}

.obstacle img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.game-ui {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding: 10px;
  color: white;
  z-index: 20;
}

.score-panel {
  display: flex;
  justify-content: space-between;
  font-size: 18px;
  background: rgba(0, 0, 0, 0.5);
  padding: 10px;
  border-radius: 5px;
}

.mobile-controls {
  position: absolute;
  bottom: 20px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}

.control-btn {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.3);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 24px;
}

.start-screen, .game-over {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.9);
  z-index: 30;
}

.game-title {
  background: linear-gradient(to right, #ff4b1f, #ff9068);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.difficulty-selector {
  margin-bottom: 20px;
  text-align: center;
}

.difficulty-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.difficulty-buttons button {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  background: #2c3e50;
  color: white;
  cursor: pointer;
}

.difficulty-buttons button.active {
  background: #ff6b6b;
}

.high-scores {
  margin-bottom: 20px;
  text-align: center;
}

.high-scores ul {
  list-style: none;
  padding: 0;
}

.new-high-score {
  color: #ff6b6b;
  font-size: 24px;
  margin: 10px 0;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.start-button, .restart-button {
  padding: 12px 24px;
  font-size: 20px;
  background: #ff6b6b;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: transform 0.2s;
}

.start-button:hover, .restart-button:hover {
  transform: scale(1.05);
}
</style>